import Vue from "vue";
import App from "./App.vue";

import router from "./router";
import store from "./store";

import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";

import "@/assets/css/base.css";
import "./assets/css/el-reset.css"

//隐式侧边菜单
import subMenu from "qf-sub-menu"
//引入进度条
import nprogress from "nprogress"
//引入进度条样式
import "nprogress/nprogress.css"

Vue.use(subMenu);
Vue.use(ElementUI);

//.vue后缀名结尾的文件，我们称之为单文件组件
Vue.config.productionTip = false;

//全局前置钩子(路由守卫)
router.beforeEach((to, from, next) => {
  nprogress.start()
  //to 即将进入的路由
  //from 即将离开的路由
  //next 放行

  //判断本地存储中是否有token
  //除了登录页，其他所有到的页面，在没有登录的情况下都不能给用户访问
  //如果有就放行，如果没有就不通过，重新跳转到登录页

  let token = localStorage.getItem("qf-token") || "";
  if (token) {//已登录
    //获取用户菜单
    if (store.state.sideMenu.length === 0) {
      store.dispatch("GET_MENULIST") //加了async 所以他是个promise<pendding>
        .then(() => {
          next({ path: to.path })
        })
    } else {
      next()
    }

  } else {
    //没有登录
    //判断是否访问的登录页
    if (to.path !== "/login") {
      next({ path: "/login" });
    } else {
      next();
    }
  }
})

//自定义鉴权指令
Vue.directive("has", {
  inserted(el, binding) {
    // console.log(el);
    // console.log(binding);
    //从本地取出用户的按钮权限
    let permission = localStorage.getItem("permissionButtons") || '[]'
    permission = JSON.parse(permission)
    // console.log(permission);

    //看permission中是否包含传入的value对应字段
    if (!permission.includes(binding.value)) {
      //先保存按钮原来的类名
      let ElclassName = el.className
      //用原来的类名加上is-disabled触发警用样式
      el.className = ElclassName + " " + "is-disabled"
      //禁用按钮
      el.disabled = true
    }
  }
})

router.afterEach((to, from) => {//全局后置钩子
  nprogress.done()
  let matched = [...to.matched]
  matched.splice(0, 1)
  // console.log(matched);
  //调用commit触发mutation，更改vuex中存储的breadCrumb
  store.commit("SET_BREADCRUMB", matched)
})

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");
